CSS 像素画的方法

前言

暴力的 div、table 堆叠不在此进行赘述,image-rendering、svg 与 canvas 不在范围内。

Box-shadow

代码写起来较为简短,也有很多的生成器。但一般需要再套个元素再外以帮助占位,浏览器缩放会影响显示效果(存在缝隙或堆叠),且不太方便自适应。

CSS Pixel Art Generator PIXEL ART TO CSS

展示柜

Linear-gradient

只需一个元素,十分方便的自适应,只需宽与高任意指定一个,甚至可以在里面写点字。但不支持透明,且代码又长又没什么生成器,写起来会不太方便。

简易生成代码

Mushroom linear-gradient
/** 代码修改自https://codepen.io/cgreinhold/pen/rNagxoK **/
const pixels = [
	["","#F00"],
	["#0F0","#00F"]
];

const pixelArt = document.getElementById("pixelart");
const width = pixels[0].length;
const height = pixels.length;

const backgroundImage = [];
const backgroundSize = [];
for (let i = 0; i < pixels.length; i++) {
	const pixel = pixels[i];
	const percent = 100 / pixel.length;
	let cont = 0;
	const backgroundParts = [];
	for (let j = 0; j < pixel.length; j++) {
		const pixelColor = pixel[j] || "#FFF";
		let backgroundImagePart = "";
		backgroundImagePart += `${pixelColor} ${cont}%`;
		cont += percent;
		backgroundImagePart += `, ${pixelColor} ${cont}%`;
		backgroundParts.push(backgroundImagePart);
	}
	backgroundImage.push(
		`linear-gradient(to right, ${backgroundParts.join(", ")})`
	);
	backgroundSize.push(`100% ${((i + 1) * 100) / height}%`);
}
pixelArt.style.aspectRatio = width / height;
pixelArt.style.backgroundImage = backgroundImage.join(",");
pixelArt.style.backgroundRepeat = "repeat-x";
pixelArt.style.backgroundSize = backgroundSize.join(",");
pixelArt.removeAttribute("id")

展示柜